<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!--按钮-->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!--角色列表-->
      <el-table :data="roleList" border stripe width="300px">
        <!--展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!--一级权限-->
            <el-row v-for="(item1 , index1) in scope.row.children"
                    :key="item1.id"
                    :class="['bd-bottom' , index1 ===0 ? 'bd-top' : '' ,  'vcenter']">

              <el-col :span="5">
                <el-tag  closable
                         @close="removeRightsById(scope.row , item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--二级权限-->
              <el-col :span="19">
                <el-row v-for="(item2 , index2) in item1.children"
                        :key="item2.id"
                        :class="[index2 === 0 ? '' : 'bd-top' , 'vcenter']">

                  <el-col :span="6">
                    <el-tag type="success"  closable
                            @close="removeRightsById(scope.row , item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--三级权限-->
                  <el-col :span="18">
                    <el-tag v-for="(item3) in item2.children"
                            :key="item3.id"
                            type="warning"
                            closable
                            @close="removeRightsById(scope.row , item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

          </template>
        </el-table-column>
        <!--索引列-->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning"
                       icon="el-icon-setting"
                       size="mini"
                       @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--分配权限的对话框-->
    <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisable"
        width="50%"
        @close="setRightDialogClosed">
      <el-tree :data="rightsList"
               :props="treeProps"
               show-checkbox
               node-key="id"
               :default-expand-all = 'true'
               :default-checked-keys = 'defKeys'
               ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisable = false">取 消</el-button>
        <el-button type="primary"
                   @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      // 所有角色列表数据
      roleList: [],
      // 控制对话框的显示与隐藏对话框
      setRightDialogVisable: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点ids数值
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取所有角色的列表
    async getRolesList() {
      const {data: res} = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表信息失败')
      }
      this.roleList = res.data
    },
    async removeRightsById(role, rightId) {
      // 弹框提示用户是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除按钮');
      }
      const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户角色失败')
      }
      // this.getRolesList() 直接调用的话会导致页面重新渲染不建议
      role.children = res.data  //删除结束后会重新将用户权限以data的形式返回
    },
    // 展示分配权限的对话框
    async showSetRightDialog    (role) {
      this.roleId = role.id
      // 获取所有权限数据
      const {data : res} = await this.$http.get('rights/tree')
      if(res.meta.status !== 200) {
        return this.$message.error('获取用户权限失败')
      }
      this.rightsList = res.data;
      // console.log(this.rightsList);
      // console.log(role)
      // 递归获取三级节点的id
      this.getLeafKeys(role , this.defKeys)

      this.setRightDialogVisable = true;
    },
    // 通过递归的形式，获取角色下所有的三级权限的id
    getLeafKeys(node , arr) {
      // 判断是否是三级节点，三级节点没有children属性
      if(!node.children) {
        return arr.push(node.id);
      }
      // 递归获取搜友三级节点
      node.children.forEach(item => this.getLeafKeys(item , arr))
    },
    // 监听弹出框是否关闭的事件
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 点击确定按钮位角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys() , ...this.$refs.treeRef.getHalfCheckedKeys()]
      // console.log(keys);
      const idStr = keys.join(',');
      // console.log(keysStr)

      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights` , {rids: idStr})
      if(res.meta.status !== 200) {
        return this.$message.error('分配角色权限失败')
      }

      this.$message.success('分配权限成功')
      // 刷新对话框
      await this.getRolesList();
      this.setRightDialogVisable = false;
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}

.bd-top {
  border-top: 1px solid #ccc;
}

.bd-bottom {
  border-bottom: 1px solid #ccc;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>